<?php
/**
 * Created by PhpStorm.
 * User: DELL-PC
 * Date: 2018/8/17
 * Time: 13:02
 */

namespace J\Schema\Collection\Element;


use J\Schema\ICollection;
use J\Schema\Syntax;

class BelongsElement extends Element
{
    public function getLabel() : string
    {
        try{
            return $this->collection->getCollection($this->name)->getLabel();
        } catch (\Throwable $e) {
            return $this->name;
        }
    }

    public function fillValue(&$rs, $raw = false)
    {
        if ($raw) {
            parent::fillValue($rs);
            return;
        }

        $column = $this->getColumnName();
        $ids = array_column_unique($rs, $column);
        try {
            $c = $this->collection->getCollection($this->name);
            $keys = $this->getRelation($c);
            $values = $c->getCurd()->setIds($ids)->setElements($keys)->select();
        } catch (\Throwable $e) {
            return ;
        }

        foreach ($rs as &$record) {
            $id = (int)$record[$column];
            if (isset($values[$id])) {
                $record[$column] = $id;
                if(is_string($keys)){
                    $record[$this->name] = $values[$id][$keys];
                }else{
                    $record[$this->name] = $values[$id];
                }
            }
        }
    }

    public function getOptions($where = true)
    {
        try {
            $c = $this->collection->getCollection($this->name);
            // 构建查询列
            $key = $this->getRelation($c);
            $fields = [$key];
            $tree = $c->getTreeKey();
            if ($tree) $fields[] = $tree;

            $rs  = $c->getCurd()->setWhere($where)->setElements($fields)->select();
        } catch (\Throwable $e) {
            return [];
        }

        $r = [];
        foreach ($rs as $row) {
            $temp = [
                'label' => $row[$key],
                'value' => $row[Syntax::KEY_ID],
            ];
            if ($tree) $temp[$c->getName()] = $row[$tree];
            $r[] = $temp;
        }
        return $r;
    }

    public function getFieldType()
    {
        return 'select';
    }

    public function isBelongs()
    {
        return true;
    }

    /**
     * 获取关联域
     *
     * @param ICollection $c
     * @return string
     */
    protected function getRelation($c)
    {
        return $this->getAttribute()->get(Syntax::KEY_RELATION, $c->getKey());
    }

    public function isTreeNode()
    {
        try{
            $c = $this->collection->getCollection($this->name);
            return $c->isTree();
        } catch (\Throwable $e) {
            return false;
        }
    }
}